<?php

/**
 * This is the model class for table "menu".
 *
 * The followings are the available columns in table 'menu':
 * @property string $id
 * @property string $type
 * @property string $parent_id
 * @property string $name
 * @property string $url
 * @property string $icon
 * @property double $sort
 * @property string $target
 * @property integer $is_absolute_url
 * @property integer $is_display
 * @property string $created_at
 * @property string $updated_at
 */
class Menu extends CActiveRecord
{
    const BACKEND_TYPE = 0;
    const FRONTEND_TYPE = 1;

    const DISPLAY_YES = 1;
    const DISPLAY_NO = 0;
    public $level;
    public $treename;

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{menu}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, url', 'required'),
			array('is_absolute_url, is_display', 'numerical', 'integerOnly'=>true),
			array('sort', 'numerical'),
			array('type, parent_id, created_at, updated_at', 'length', 'max'=>11),
			array('name, url, icon, target', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, type, parent_id, name, url, icon, sort, target, is_absolute_url, is_display, created_at, updated_at', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => '自增id',
			'type' => '菜单类型.0后台,1前台',
			'parent_id' => '上级菜单id',
			'name' => '名称',
			'url' => 'url地址',
			'icon' => '图标',
			'sort' => '排序',
			'target' => '打开方式._blank新窗口,_self本窗口',
			'is_absolute_url' => '是否绝对地址',
			'is_display' => '是否显示.0否,1是',
			'created_at' => '创建时间',
			'updated_at' => '最后修改时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('parent_id',$this->parent_id,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('url',$this->url,true);
		$criteria->compare('icon',$this->icon,true);
		$criteria->compare('sort',$this->sort);
		$criteria->compare('target',$this->target,true);
		$criteria->compare('is_absolute_url',$this->is_absolute_url);
		$criteria->compare('is_display',$this->is_display);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('updated_at',$this->updated_at,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Menu the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    /**
     * 提前做数据处理，保存数据
     * @return bool
     */
    public function beforeSave()
    {
        parent::beforeSave(); // TODO: Change the autogenerated stub

        if($this->isNewRecord){
            $this->created_at = time();
        }else{
            $this->updated_at = time();
        }
        return true;
    }


    /**
     * @param $type
     * @return array
     */
    protected static function _getMenus($type)
    {
        return $data = array_map(function ($record){return $record->attributes;},self::model()->findAll(array('order'=>'sort asc,parent_id asc','condition'=>'type=:type','params'=>array(':type'=>$type))));
    }

    /**
     * @param int $type
     * @return array
     */
    public static function getMenus($type=self::BACKEND_TYPE)
    {
        $categories = self::_getMenus($type);
        $familyTree = new FamilyTree($categories);
        $array = $familyTree->getDescendants(0);
        //根据字段id对数组$array进行升序排列
        //$last_names = array_column($array,'id','id');
        //array_multisort($last_names,SORT_ASC,$array);
        return FamilyTree::arrayIndex($array,'id');
    }

    /**
     * 将分类转换为数组
     * @param int $parentId
     * @param array $array
     * @param int $level
     * @param int $add
     * @param string $repeat
     * @return array
     */
    public static function getMenuTree($parentId = 0, $array = array(), $level = 0, $add = 2, $repeat = '&nbsp;&nbsp;') {
        $str_repeat = '';
        if ($level) {
            for($j = 0; $j < $level; $j ++) {
                $str_repeat .= $repeat;
            }
        }
        $newArray = array ();
        $tempArray = array ();
        foreach ( (array) $array as $v ) {
            if ($v ['parent_id'] == $parentId) {
                $newArray [] = array (
                    'id' => $v['id'],
                    'type' => $v['type'],
                    'parent_id' => $v['parent_id'],
                    'name' => $v['name'],
                    'url' => $v['url'],
                    'icon' => $v['icon'],
                    'sort' => $v['sort'],
                    'target' => $v['target'],
                    'is_absolute_url' => $v ['is_absolute_url'],
                    'is_display' => $v['is_display'],
                    'created_at' => $v['created_at'],
                    'updated_at' => $v['updated_at'],
                    'str_repeat' => $str_repeat,
                    'level' => $level,
                );

                $tempArray = self::getMenuTree ( $v ['id'], $array, ($level + $add) );
                if ($tempArray) {
                    $newArray = array_merge ( $newArray, $tempArray );
                }
            }
        }
        return $newArray;
    }


    /**
     * @return string
     */
    public function getMenuUrl()
    {
        $url = "";
        if( !$this->is_absolute_url ) {
            if( strlen($this->url) > 0 ){
                $firstCharacter = $this->url[0];
                if( in_array($firstCharacter, ['[', '{']) ){
                    $temp = @json_decode($this->url, true);
                    if( $temp === null ){
                        Yii::t("app", "Menu id ({$this->id}) url is incorrect json format");
                    }
                    //$temp = "'article/index',array('cat'=>'news')";
                    //var_dump(json_encode($temp));exit();
                    $url = Yii::app()->createUrl($temp);
                }else{
                    $url = Yii::app()->createUrl($this->url);
                }
            }
        }else{
            $url = Yii::app()->createUrl($this->url);
        }
        //$url = Yii::app()->createUrl('article/index',array('cat'=>'news'));

        //var_dump($url);exit;
        return $url;
    }

}
